
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Expressions;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;

using System.Linq.Dynamic.Core;
 using Microsoft.EntityFrameworkCore; 

using DualControl.CycleCheckTasks.Authorization;
using DualControl.CycleCheckTasks.Dtos;
using DualControl.CycleCheckTasks;
using DualControl.Authorization.Users;
using DualControl.Authorization.Roles;
using Abp.Dapper.Repositories;
using Abp.Runtime.Session;

namespace DualControl.CycleCheckTasks
{
    /// <summary>
    /// CycleCheckTask应用层服务的接口实现方法  
    ///</summary>
   // [AbpAuthorize(CycleCheckTaskAppPermissions.CycleCheckTask)]
    public class CycleCheckTaskAppService : DualControlAppServiceBase, ICycleCheckTaskAppService
    {
        private readonly IRepository<CycleCheckTask, int>_cyclechecktaskRepository;

        private readonly ICycleCheckTaskManager _cyclechecktaskManager;

        //使用Dapper存储
        private readonly IDapperRepository<User, long> _userdapperRepository;

        /// <summary>
        /// 构造函数 
        ///</summary>
        public CycleCheckTaskAppService(IRepository<CycleCheckTask, int> cyclechecktaskRepository , ICycleCheckTaskManager cyclechecktaskManager, IDapperRepository<User, long> userdapperRepository)
        {
            _cyclechecktaskRepository = cyclechecktaskRepository;
            _cyclechecktaskManager = cyclechecktaskManager;
            _userdapperRepository = userdapperRepository;
        }


        //查询用户排查任务信息，包括用户名、部门名、岗位名、角色名等，前端显示用。

        [AbpAuthorize(CycleCheckTaskAppPermissions.CycleCheckTask)]
        public async Task<PagedResultDto<CycleCheckTaskListDto>> GetPageCycleCheckTaskWithDapper(GetCycleCheckTasksInput input)
        {
            var tenantid = AbpSession.TenantId;
            var sql = "SELECT cct.Id, cct.UserId, abpusers.Name, cct.StartTime, cct.EndTime, cct.CheckCycle, cct.CheckState, cct.`Desc`, cct.TenantId, cct.ReportingTime,uou.OrganizationUnitId, ou.DisplayName as OuName, userposts.PostId, posts.`Name` as PostName, abpuserroles.RoleId, abproles.DisplayName as RoleName from cyclechecktasks as cct LEFT JOIN abpusers on cct.UserId = abpusers.Id LEFT JOIN abpuserorganizationunits as uou on cct.UserId = uou.UserId LEFT JOIN abporganizationunits as ou on uou.OrganizationUnitId = uou.Id  LEFT JOIN userposts on userposts.UserId = cct.UserId LEFT JOIN abpuserroles on  cct.UserId = abpuserroles.UserId LEFT JOIN abproles on abproles.Id = abpuserroles.RoleId LEFT JOIN posts on userposts.PostId = posts.Id where cct.TenantId =" + tenantid + " AND cct.UserId ="+AbpSession.UserId + " GROUP BY cct.Id  ORDER BY cct.Id";

            var query = await _userdapperRepository.QueryAsync<CycleCheckTaskListDto>(sql);

            var cyclechecktaskscount = query.Count();

            var cyclechecktasks = query.OrderByDescending( a=>a.EndTime)
               .Skip(input.SkipCount)                
                .Take(input.MaxResultCount)
                .ToList();
            return new PagedResultDto<CycleCheckTaskListDto>(cyclechecktaskscount, cyclechecktasks);

        }





        /// <summary>
        /// 获取CycleCheckTask的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(CycleCheckTaskAppPermissions.CycleCheckTask)]
        public async Task<PagedResultDto<CycleCheckTaskListDto>> GetPagedCycleCheckTasks(GetCycleCheckTasksInput input)
        {

            var query = _cyclechecktaskRepository.GetAll();
            // TODO:根据传入的参数添加过滤条件

            var cyclechecktaskCount = await query.CountAsync();

            var cyclechecktasks = await query
                    .OrderBy(input.Sorting).AsNoTracking()
                    .PageBy(input)
                    .ToListAsync();

            // var cyclechecktaskListDtos = ObjectMapper.Map<List <CycleCheckTaskListDto>>(cyclechecktasks);
            var cyclechecktaskListDtos = cyclechecktasks.MapTo<List<CycleCheckTaskListDto>>();

            return new PagedResultDto<CycleCheckTaskListDto>(cyclechecktaskCount,cyclechecktaskListDtos);
        }


        /// <summary>
        /// 通过指定id获取CycleCheckTaskListDto信息
        /// </summary>
        [AbpAuthorize(CycleCheckTaskAppPermissions.CycleCheckTask)]
        public async Task<CycleCheckTaskListDto> GetCycleCheckTaskByIdAsync(EntityDto<int> input)
        {
            var entity = await _cyclechecktaskRepository.GetAsync(input.Id);

            return entity.MapTo<CycleCheckTaskListDto>();
        }

        /// <summary>
        /// MPA版本才会用到的方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(CycleCheckTaskAppPermissions.CycleCheckTask)]
        public async Task<GetCycleCheckTaskForEditOutput> GetCycleCheckTaskForEdit(NullableIdDto<int> input)
        {
            var output = new GetCycleCheckTaskForEditOutput();
            CycleCheckTaskEditDto cyclechecktaskEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _cyclechecktaskRepository.GetAsync(input.Id.Value);

                cyclechecktaskEditDto = entity.MapTo<CycleCheckTaskEditDto>();

                //cyclechecktaskEditDto = ObjectMapper.Map<List <cyclechecktaskEditDto>>(entity);
            }
            else
            {
                cyclechecktaskEditDto = new CycleCheckTaskEditDto();
            }

            output.CycleCheckTask = cyclechecktaskEditDto;
            return output;
        }

        
        //该方法配置为后台任务自动调用执行，所以没有权限要求，生成的前端JS方法要去掉
        //周期执行的方法，查询所有的用户，然后为每个用户添加一条排查任记录，包括用户Id、部门、岗位、角色、排查周期、开始结束时间、提交时间等字段。
        public async Task  GenerateCycleCheckTask()
        {

            var userlist =  await GetUsers();
            CycleCheckTaskEditDto cycleCheckTaskEditDto; 
            foreach (UserForCycleCheckTask user in userlist)
            {
                cycleCheckTaskEditDto = new CycleCheckTaskEditDto
                {
                    UserId = user.Id,
                    TenantId = user.TenantId,
                    StartTime = DateTime.Now,
                    EndTime = DateTime.Now.AddDays(1),
                    CheckCycle = Common.CheckCycle.每天,
                    CheckState = Common.CheckState.未排查
                };

                await CreateCycleCheckTaskAsync(cycleCheckTaskEditDto);
            }

        }

        //查询用户信息，包括部门、岗位、角色，可以根据这些信息为不同用户生成不同的任务。

        private async Task <List<UserForCycleCheckTask>> GetUsers()
        {          
            var query = await _userdapperRepository.QueryAsync<UserForCycleCheckTask>("SELECT  abpusers.Id,abpusers.Name,abpusers.TenantId,uou.OrganizationUnitId,userposts.PostId,abpuserroles.RoleId from abpusers LEFT JOIN abpuserorganizationunits as uou on abpusers.id = uou.UserId  LEFT JOIN userposts on userposts.UserId = abpusers.Id LEFT JOIN abpuserroles on abpusers.Id = abpuserroles.UserId where AbpUsers.TenantId >= 0 GROUP BY abpusers.Id  ORDER BY abpusers.Id");
            var userpostorgListDto = query.ToList();
            return new List<UserForCycleCheckTask>(userpostorgListDto);
        }


        /// <summary>
        /// 添加或者修改CycleCheckTask的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(CycleCheckTaskAppPermissions.CycleCheckTask)]
        public async Task CreateOrUpdateCycleCheckTask(CreateOrUpdateCycleCheckTaskInput input)
        {

            if (input.CycleCheckTask.Id.HasValue)
            {
                await UpdateCycleCheckTaskAsync(input.CycleCheckTask);
            }
            else
            {
                await CreateCycleCheckTaskAsync(input.CycleCheckTask);
            }
        }

       

        /// <summary>
        /// 新增CycleCheckTask
        /// </summary>
        
        protected virtual async Task<CycleCheckTaskEditDto> CreateCycleCheckTaskAsync(CycleCheckTaskEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = ObjectMapper.Map<CycleCheckTask>(input);

            entity = await _cyclechecktaskRepository.InsertAsync(entity);
            return entity.MapTo<CycleCheckTaskEditDto>();
        }

        /// <summary>
        /// 编辑CycleCheckTask
        /// </summary>
        [AbpAuthorize(CycleCheckTaskAppPermissions.CycleCheckTask)]
        protected virtual async Task UpdateCycleCheckTaskAsync(CycleCheckTaskEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _cyclechecktaskRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            // ObjectMapper.Map(input, entity);
            await _cyclechecktaskRepository.UpdateAsync(entity);
        }



        /// <summary>
        /// 删除CycleCheckTask信息的方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(CycleCheckTaskAppPermissions.CycleCheckTask)]
        public async Task DeleteCycleCheckTask(EntityDto<int> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _cyclechecktaskRepository.DeleteAsync(input.Id);
        }



        /// <summary>
        /// 批量删除CycleCheckTask的方法
        /// </summary>
        [AbpAuthorize(CycleCheckTaskAppPermissions.CycleCheckTask)]
        public async Task BatchDeleteCycleCheckTasksAsync(List<int> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _cyclechecktaskRepository.DeleteAsync(s => input.Contains(s.Id));
        }


        /// <summary>
        /// 导出CycleCheckTask为excel表,等待开发。
        /// </summary>
        /// <returns></returns>
        //public async Task<FileDto> GetCycleCheckTasksToExcel()
        //{
        //	var users = await UserManager.Users.ToListAsync();
        //	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
        //	await FillRoleNames(userListDtos);
        //	return _userListExcelExporter.ExportToFile(userListDtos);
        //}

        //// custom codes

        //// custom codes end

    }
}


